package com.pig4cloud.pigx.common.security.mobile;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.pig4cloud.pigx.common.security.component.exceptionProcessed.PigxCommenceAuthExceptionEntryPoint;
import com.pig4cloud.pigx.common.security.resource.component.PigxResourceServerAutoConfiguration;
import com.pig4cloud.pigx.common.security.resource.component.beanDefinitionRegistrar.PigxLocalResourceServerConfigurerAdapter;
import com.pig4cloud.pigx.common.security.service.PigxUserDetailsService;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutFilter;

/**
 * @description: 手机号登录配置入口
 * @Author 兔子不吃窝边曹
 * @create 2022/8/10 11:36
 **/
@Getter
@Setter
public class MobileSecurityConfigurer extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private AuthenticationSuccessHandler mobileLoginSuccessHandler;

    @Autowired
    private PigxUserDetailsService userDetailsService;

    @Override
    public void configure(HttpSecurity http) {
        MobileAuthenticationFilter mobileAuthenticationFilter = new MobileAuthenticationFilter();

        mobileAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));

        mobileAuthenticationFilter.setAuthenticationSuccessHandler(mobileLoginSuccessHandler);

        /**
         * 关于setAuthenticationEntryPoint的时候使用new一个对象，而不是通过 @Autowired注入进来，毕竟我们在
         * {@link PigxCommenceAuthExceptionEntryPoint}类中添加了@Component注解
         * <P>
         *    我也想不太明白，心里的想法是pigx-auth扫描的路径是com.pig4cloud.pigx.auth，而PigxCommenceAuthExceptionEntryPoint在com.pig4cloud.pigx.common.security下
         *    <p>
         *         在{@link PigxLocalResourceServerConfigurerAdapter}中可以通过 @Autowired注入进来。
         *         我想是{@link PigxResourceServerAutoConfiguration}的注解@ComponentScan("com.pig4cloud.pigx.common.security")起的效果吧
         *    </p>
         * </P>
         */
        mobileAuthenticationFilter.setAuthenticationEntryPoint(new PigxCommenceAuthExceptionEntryPoint(objectMapper));

        MobileAuthenticationProvider mobileAuthenticationProvider = new MobileAuthenticationProvider();
        mobileAuthenticationProvider.setUserDetailsService(userDetailsService);
        http.authenticationProvider(mobileAuthenticationProvider)
                .addFilterAfter(mobileAuthenticationFilter, LogoutFilter.class);
    }

}
